//index.js
const util = require('../../utils/util.js');
import * as utils from '../../utils/util.js';
import request from '../../utils/http.js';
import upload from '../../utils/upload.js';
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
//获取应用实例
const app = getApp()
Page({
  data: {
    userInfo: {},
    isLogin:false,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    babyList:[],
    changeBabyData:{},
    ageStr:'',
    currentIndex:0,
    //宝宝近期接种计划数据
    shortTermPlan:[],
    //宝宝成长记录，档案
    babyGrowthRecord:[],
    //计划接种事件
    planTime:'',
    week:'',
    showType:0,
    description: '',
    indexbgImgURL:'',
    hasInsurance:false,
    isExpired:false,
  },
  onShow () {
    let isLogin = wx.getStorageSync('isLogin') && app.globalData.isLogin;
    if (isLogin) {
      let coverImg = wx.getStorageSync('coverImg')
      this.getBabyList()//获取宝宝列表
      this.setData({
        indexbgImgURL: coverImg,
        isLogin: isLogin,
      })
    }
  },
  setFMimgs(){
    let that = this;
    wx.showActionSheet({
      itemList: ['拍摄','从手机相册选择'],
      success:function(res){
        console.log(res)
        if(res.tapIndex == 0){
          //拍摄
          wx.chooseImage({
            count:1,
            sizeType: ['original'],
            sourceType: ['camera'],
            success: function(e) {
              wx.showLoading({
                title: '正在上传',
              })
              let imgUrl = e.tempFilePaths[0];
              that.uploadIndexImg(imgUrl)
            },
            fail:function(err){
              return 
            }
          })
        } else if (res.tapIndex == 1){
          wx.chooseImage({
            count: 1,
            sizeType: ['original'],
            sourceType: ['album'],
            success: function (e) {
              wx.showLoading({
                title: '正在上传',
              })
              let imgUrl = e.tempFilePaths[0];
              that.uploadIndexImg(imgUrl)
            },
            fail: function (err) {
              return
            }
          })
        }
      },
      fail:function(err){
        console.log(err)
      }
    })
  },
  //上传首页背景图片
  uploadIndexImg(url){
    upload(url,'pic_root').then(res=>{
      console.log(`上传图片结果`)
      console.log(res)
      if (res.status){
        wx.hideLoading()
        let url = res.url;
        this.setData({
          indexbgImgURL: url
        })
        wx.setStorageSync('coverImg', url)
        utils.HttpRequst(false, '/baby-cloud-system/mobileUser/editUserBg', 'post',{ bgUrl: url},res=>{
          if(res.data.code !== 200){
            wx.showToast({
              title: '网络出错,请重试',
            })
            return
          }
        })
      }
    })
  },
  //获取宝宝列表
  getBabyList(){
    utils.HttpRequst(true, "/baby-cloud-base/mobileBabyInfo/listAll","post",{},(res)=>{
      if (res.data.code == 200 && res.data.data.length > 0) {
        let index = this.data.currentIndex
        let currentBaby = res.data.data[index]
        this.setData({
          babyList: res.data.data,
          changeBabyData: currentBaby,
          ageStr: utils.getBirthSlot(currentBaby.birthday.split(" ")[0])
        })
        // wx.setStorageSync('babyList', res.data.data)
        //默认请求第一个宝宝的接种计划   参数宝宝id
        this.getBabyVaccinationPlan(currentBaby.id)
        //获取宝宝成长记录，宝宝档案
        this.getBabyGrowthRecord(currentBaby.id)
        //获取宝宝成长影像  
        this.getBabyGrowthMV(currentBaby.id)
        //获取该宝宝是否领取保单
        this.getBabyInsurance(currentBaby.id)
      } else if (res.data.code == 200 && res.data.data.length == 0){
        this.setData({
          babyList: res.data.data
        })
        wx.setStorageSync('babyList', res.data.data)
      }
    })
  },
  //选择宝宝头像时 需要展示的数据
  changeBabyHeader(e){
    let index = e.target.dataset.idx
    wx.setStorageSync("currentBabyIndex", index);
    let currentBaby = this.data.babyList[index]
    this.setData({
      currentIndex: index,
      changeBabyData: currentBaby,
      ageStr: utils.getBirthSlot(currentBaby.birthday.split(" ")[0])
    })
    this.getBabyVaccinationPlan(currentBaby.id) //获取宝宝接种计划
    this.getBabyGrowthRecord(currentBaby.id) //获取宝宝成长记录
    this.getBabyGrowthMV(currentBaby.id)//获取宝宝成长影像
    this.getBabyInsurance(currentBaby.id)//获取该宝宝是否领取保单
  },
  //获取宝宝接种计划
  getBabyVaccinationPlan(babyId){
    utils.HttpRequst(false, '/baby-cloud-base/mobileVaccinePlan/getNextPlan', 'post', { babyId},res=>{
      if (res.data.code == 200) {
        //处理第一针信息
        if(res.data.data.length>0){
          let one = res.data.data[0];
          let date = one.planTime.split(" ")[0];
          let arr = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
          let day = utils.getNowFormatDate();
          let planDay;
          const d = utils.datedifference(date, day);
          if (d == 0) {
            planDay = '今天'
          } else if (d == 1) {
            planDay = '明天'
          } else {
            planDay = d + '天后'
          }
          this.setData({
            planTime: date,
            week: arr[new Date(date).getDay()],
            shortTermPlan: res.data.data,
            planDay
          });
        }else{
          this.setData({
            planTime: '',
            week: '',
            shortTermPlan: '',
            planDay:''
          });
        }
      }
    })
  },
  //获取宝宝成长记录
  getBabyGrowthRecord(babyId){
    utils.HttpRequst(false, '/baby-cloud-base/mobileGrowthRecord/list', 'post', { babyId},res=>{
      if (res.data.code == 200) {
        this.setData({
          babyGrowthRecord: res.data.data
        })
      }
    })
  },
  //获取宝宝成长影像
  getBabyGrowthMV(babyId){
    utils.HttpRequst(false, '/baby-cloud-base/mobileGrowthVideo/list', 'post', { babyId},res=>{
      if (res.data.code == 200) {
        //在此处理首页展示成长影像数据
        let data = res.data.data;
        let imgs,showType,descriptions;
        if (data.length >0){
          if (data[0].growthType == 0) {
            imgs = data[0].picJson.split(",").slice(0, 2);
            showType = 0;
            descriptions = data[0].description
          } else {
            imgs = data[0].picJson;
            showType = 1;
            descriptions = data[0].description
          }
          this.setData({
            babyGrowthMV: res.data.data,
            showdata: imgs,
            showType: showType,
            description: descriptions
          })
        } else {
          this.setData({
            showType: 2
          })
        }
      }
    })
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  //查看电子保单
  viewPolicy() {
    Dialog.alert({
      message: '请关注“横琴人寿在线”微信公众号，使用您的投保手机号注册并登录，在我的-我的信息-我的保单中可以查看电子保单。'
    }).then(() => {
    });
  },
  //申请理赔
  claimSettlement() {
    Dialog.alert({
      message: '请关注“横琴人寿在线”微信公众号，使用您的投保手机号注册并登录，在精彩·服务-服务大厅-理赔报案菜单中申请理赔。'
    }).then(() => {
    });
  },
  //跳转接种计划页
  openPlanDetail: function () {
    wx.switchTab({
      url: '/pages/accination-plan/accination-plan'
    })
  },
  //跳转宝宝全部接种计划页
  openAllPlan() {
    let id = this.data.changeBabyData.id;
    let name = this.data.changeBabyData.name
    wx.navigateTo({
      url: '/pages/accination-allPlan/accination-allPlan?babyId=' + id + "&name=" + name 
    });
    
  },
  // 添加宝宝
  openAddBaby() {
    //检测是否登录
    if (this.data.isLogin) { }
      wx.navigateTo({
        url: '/pages/addBaby/addBaby',
      })
    
  },
  //添加宝宝成长记录
  addGrowthRecord (e) {
    console.log(e)
    let active = e.currentTarget.dataset.active;
    let babyId = this.data.changeBabyData.id;
    //检测是否登录
    if (this.data.isLogin){
      wx.navigateTo({
        url: '/pages/growthRecord/growthRecord?babyId=' + babyId + "&active=" + active,
      })
    } else {
      wx.navigateTo({
        url: '/pages/quickLogin/quickLogin'
      });
    }
  },

  //跳转成长影像
  openGrowthRecord(){
    let babyId = this.data.changeBabyData.id;
    wx.navigateTo({
      url: '/pages/growthRecord/growthRecord?babyId=' + babyId + '&active=0',
    })
  },
  //跳转领取保险页
  openReceive: function () {
    if (JSON.stringify(this.data.changeBabyData)=='{}'){
      Toast('添加宝宝信息后可领取')
      return;
    }
    let nowDay = new Date();
    let babyDay = new Date(this.data.changeBabyData.birthday.replace(/-/g, "/"));
    let days = nowDay.getTime() - babyDay.getTime();
    let day = parseInt(days / (1000 * 60 * 60 * 24))+1;
    console.log(day)
    wx.navigateTo({
      url: '/pages/receiveInsurance/receiveInsurance?dabyData=' + encodeURIComponent(JSON.stringify(this.data.changeBabyData)) + '&babybirthDays=' + day
    })
  },

  //测试扫描二维码直接进入领取保单页
  // openReceive: function () {
  //   wx.navigateTo({
  //     url: '/pages/receiveInsuranceNew/receiveInsuranceNew'
  //   })
  // },

  getBabyInsurance(id){
    let data={
      status:1,
      babyId:id
    }
    utils.HttpRequst(false, "/baby-cloud-base/babyInsurance/list", "post", data, (res) => {
      if (res.data.code == 200) {
        if(res.data.data.length>0){
          let endTime = res.data.data[0].effectInterval.split("至")[1]+" 00:00:00"
          let endDate = new Date(endTime.replace(/-/g, "/")).getTime();
          let currentDate = new Date().getTime();
          let timeCha = parseInt((currentDate - endDate) / (1000 * 60 * 60 * 24));
          if(timeCha>0){
            this.setData({
              hasInsurance: true,
              isExpired:true
            })
          }else{
            this.setData({
              hasInsurance: true,
              isExpired: false
            })
          }
        }else{
          this.setData({
            hasInsurance: false
          })
        }
      }else{
        Toast(res.data.message)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
onLoad(options) {
    let that = this;
  if (options.scene && !app.globalData.isLogin){
    wx.navigateTo({
      url: '/pages/login/login'
    })
    }
    //获取关系id
    if (options && options.relationId){
      let relationId = options.relationId || '';
      wx.setStorageSync('relationId', relationId);
      //判断是否登录
      //已登录，执行再次登录，传入relationId
      let isLogin = wx.getStorageSync('isLogin') || false;
      if (isLogin){
        utils.wxLogin((res) => {
          wx.setStorageSync("telNum", res.data.data.account);
          wx.setStorageSync('usertoken', res.data.data.a_token)
          wx.setStorageSync('isLogin', true)
          app.globalData.isLogin = true;
          that.onShow()
        })
      }
      //否则不做任何处理
      
    }
    utils.HttpRequst(false, '/baby-cloud-system/dictType/listAll', 'post', {}, res => {
      if (res.data.code == 200) {
        let obj = {}
        res.data.data.forEach((item => {
          for (let p in item) {
            obj[p] = item[p]
          }
        }))
        wx.setStorageSync('dict', obj)
      }
    })
    wx.setStorageSync("currentBabyIndex", 0);
  },
  loginSuccess(e){
    this.setData({
      isLogin:e.detail
    })
    this.onLoad();
    this.onShow();
  },
  onShareAppMessage: function () {
    return {
      title: '宝贝疫苗接种助手',
      path: '/pages/index/index', //这里拼接需要携带的参数
      imageUrl: '/images/appBanner.png',
      success: function (res) {
        console.log("转发成功" + res);
      }
    }
  }
})
